//
//  NSObject+SQModel_id.m
//  SQLiteForOCModel
//
//  Created by 唐健 on 2018/10/3.
//  Copyright © 2018年 唐健. All rights reserved.
//

#import "NSObject+SQModel_id.h"
#import <objc/runtime.h>
#import <MJExtension/NSObject+MJProperty.h>
#import "SQManager.h"








@implementation NSObject (SQModel_id)

- (NSString *)SQModel_id{
    NSAssert(NO, @"使用SQModel数据库存储的模型须实现该方法 _func_ - (NSString *)SQModel_id;");
    return nil;
}

+ (NSString *)SQModel_tabName{
    return [NSString stringWithFormat:@"%@_tab",NSStringFromClass(self)];
}

- (NSDictionary *)sq_propertyKeyValues{
    //获取模型的有效键值对
     NSMutableDictionary *sq_KeyValues = [self mj_keyValues].mutableCopy;
    
    //移除被屏蔽的类的解析树
    NSArray *ignoredPropertyClasses = @[
                                        [UIImage class]
                                        ];
    
    NSArray *allKeys = sq_KeyValues.allKeys;
    for(NSString *key in allKeys){
        id value = [self valueForKey:key];
        for(Class class in ignoredPropertyClasses){
            if([value isMemberOfClass:class] || [class isKindOfClass:[UIView class]] ){
                [sq_KeyValues removeObjectForKey:key];
            }
        }
    }
    
   
    
    
    sq_KeyValues = [[self class] convertValueFromDictOrArrToJsonString:sq_KeyValues].mutableCopy;
    
    //加入使用者指定的主键
    NSString *sq_Model_id = [self SQModel_id];
    NSAssert(sq_Model_id.length > 0, @"sq_Model_id 不能为空！");
    [sq_KeyValues setObject:sq_Model_id forKey:SQModel_idMarkKey];
    
    //加入最后更新时间
    NSNumber *updateTime = @([[NSDate date] timeIntervalSince1970]);
    [sq_KeyValues setObject:updateTime forKey:SQModel_updateTimeKey];
    
    //加入根据当前类名合成对应的表名
    NSString *tableName = [[self class] SQModel_tabName];
    [sq_KeyValues setObject:tableName forKey:SQModel_tabNameKey];
    return sq_KeyValues;
}


/**
 把value中的NSDictionary和NSArray转化为JSON字符串
 */
+ (NSDictionary *)convertValueFromDictOrArrToJsonString:(NSDictionary *)originKeyValues{
    NSMutableDictionary *convertKeyValues = [NSMutableDictionary new];
    
    [originKeyValues enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {
        if([obj isKindOfClass:[NSArray class]]||[obj isKindOfClass:[NSDictionary class]]){
            NSString *newObj = [[NSString alloc] initWithData:[NSJSONSerialization dataWithJSONObject:obj options:0 error:nil] encoding:NSUTF8StringEncoding];
            NSString *newKey = [NSString stringWithFormat:@"%@%@",key,JsonConvertMarkKey];
            [convertKeyValues setObject:newObj forKey:newKey];
        }else{
            [convertKeyValues setObject:obj forKey:key];
        }
        
    }];
    return convertKeyValues;
}

/**
 把value中的JSON字符串转成NSDictionary和NSArray
 */
+ (NSDictionary *)restoreValueFromJsonStringToDictOrArr:(NSDictionary *)originKeyValues{
      NSMutableDictionary *convertKeyValues = [NSMutableDictionary new];
    [originKeyValues enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {
        
        if([obj isKindOfClass:[NSString class]] &&[((NSString *)key) containsString:JsonConvertMarkKey]){
            id newObj = [NSJSONSerialization JSONObjectWithData:[((NSString *)obj) dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];
            NSString *newKey = [key stringByReplacingOccurrencesOfString:JsonConvertMarkKey withString:@""];
            [convertKeyValues setObject:newObj forKey:newKey];
        }else{
            [convertKeyValues setObject:obj forKey:key];
        }
    }];
    return convertKeyValues;
}



#pragma mark - SELECT

/**
 根据主键查询（必须指定主键）
 */
+ (void)sq_selectForSQModel_id:(NSString *)SQModel_id selectResult:(void (^)(id obj))result{
    [SQManager SQDB_SELECT_WithSQModel_id:(NSString *)SQModel_id tabName:[self SQModel_tabName] selectResult:^(NSDictionary *sqDict) {
            NSDictionary *dic = [self restoreValueFromJsonStringToDictOrArr:sqDict];
            id obj = [[self class] mj_objectWithKeyValues:dic];
            result(obj);
    }];
}

+ (void)sq_selectAllSQModelSelectResult:(void (^)(NSArray *objs))result{
    [SQManager SQDB_SELECT_AllSQModelTabName:[self SQModel_tabName] selectResult:^( NSArray *dictArr) {
            id objs = [[self class] mj_objectArrayWithKeyValuesArray:dictArr];
            result(objs);
    }];
}




#pragma mark - INSERT UPDATE

- (void)sq_save:(void (^)(BOOL))saveResult{
    [[self class] sq_insert_WithSQModel_keyAndValue:[self sq_propertyKeyValues] insertResult:^(BOOL isSuccess) {
        saveResult(isSuccess);
    }];
}

+ (void)sq_save:(NSObject *)obj saveResult:(void (^)(BOOL))result{
    [self sq_insert_WithSQModel_keyAndValue:[obj sq_propertyKeyValues] insertResult:^(BOOL isSuccess) {
        result(isSuccess);
    }];
}
+ (void)sq_insert_WithSQModel_keyAndValue:(NSDictionary *)SQModel_keyAndValue insertResult:(void (^)(BOOL isSuccess))result{
    //1.插入空键值无意义
    //2.插入前 要求已经自定义了主键
    if(SQModel_keyAndValue.allKeys.count == 0 || [SQModel_keyAndValue.allKeys containsObject:SQModel_idMarkKey] == NO){
        result(NO);
        return;
    }
    [SQManager SQDB_INSERT_WithkeyAndValue:SQModel_keyAndValue insertResult:^(BOOL isSuccess) {
        result(isSuccess);
    }];
    
}





#pragma mark - DELETE

+ (void)sq_deleteForSQModel_id:(NSString *)SQModel_id deleteResult:(void (^)(BOOL isSuccess))result{
    [SQManager SQDB_DELETE_WithSQModel_id:(NSString *)SQModel_id tabName:[self SQModel_tabName] deleteResult:^(BOOL isSuccess) {
        result(isSuccess);
    }];
}

+ (void)sq_deleteAllSQModelDeleteResult:(void (^)(BOOL isSuccess))result{
    [SQManager SQDB_DELETE_WithSQModelWithTabName:[self SQModel_tabName] deleteResult:^(BOOL isSuccess) {
        result(isSuccess);
    }];
}



@end
